import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export type UserStateType = {
  username: string
  nickname: string
}

const initialState: UserStateType = {
  username: JSON.parse(localStorage.getItem('user') as string)?.username || '',
  nickname: JSON.parse(localStorage.getItem('user') as string)?.nickname || '',
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 登录
    loginReducer: (state, action: PayloadAction<UserStateType>) => {
      // @reduxjs/toolkit内置immutable，所以这里可以直接修改state
      localStorage.setItem('user', JSON.stringify(action.payload))
      state.username = action.payload.username
      state.nickname = action.payload.nickname
    },
    // 登出
    logoutReducer: state => {
      state = initialState
      localStorage.removeItem('user')
    },
  },
})

export const { loginReducer, logoutReducer } = userSlice.actions
export default userSlice.reducer
